/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.ems.web;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.MapUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.druid.Constants;
import com.thinkgem.jeesite.common.config.Global;
import com.thinkgem.jeesite.common.constant.Constant;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.ems.entity.EmsCart;
import com.thinkgem.jeesite.modules.ems.entity.EmsCartHis;
import com.thinkgem.jeesite.modules.ems.entity.EmsCartHisListBean;
import com.thinkgem.jeesite.modules.ems.entity.EmsOrder;
import com.thinkgem.jeesite.modules.ems.service.EmsCartHisService;
import com.thinkgem.jeesite.modules.ems.service.EmsCartService;
import com.thinkgem.jeesite.modules.ems.service.EmsOrderService;

/**
 * 订单Controller
 * @author zad
 * @version 2018-01-25
 */
@Controller
@RequestMapping(value = "${adminPath}/ems/emsOrder")
public class EmsOrderController extends BaseController {

	@Autowired
	private EmsOrderService emsOrderService;
	@Autowired
	private EmsCartHisService emsCartHisService;
	@Autowired
	private EmsCartService emsCartService;
	
	@ModelAttribute
	public EmsOrder get(@RequestParam(required=false) String id) {
		EmsOrder entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = emsOrderService.get(id);
		}
		if (entity == null){
			entity = new EmsOrder();
		}
		return entity;
	}
	
	@RequiresPermissions("ems:emsOrder:view")
	@RequestMapping(value = {"list", ""})
	public String list(EmsOrder emsOrder, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<EmsOrder> page = emsOrderService.findPage(new Page<EmsOrder>(request, response), emsOrder); 
		model.addAttribute("page", page);
		return "modules/ems/emsOrderList";
	}

	@RequiresPermissions("ems:emsOrder:view")
	@RequestMapping(value = "form")
	public String form(EmsOrder emsOrder, Model model) {
		model.addAttribute("emsOrder", emsOrder);
		return "modules/ems/emsOrderForm";
	}

	@RequiresPermissions("ems:emsStudent:edit")
	@RequestMapping(value = "save")
	public String save(EmsCartHisListBean cartListHisBean,EmsOrder emsOrder, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, emsOrder)){
			return form(emsOrder, model);
		}
		
		// add by zad 新增时，设置订单名称、订单编号和订单状态
		if(null != emsOrder && StringUtils.isBlank(emsOrder.getId()))
		{
			emsOrder.setName("报名订单");
			//生成订单号
	    	String orderNo=DateUtils.formatDate(new Date(),"yyyyMMddHHmmssSSS");
	    	emsOrder.setOrderNo(orderNo);
	    	// 是否后台订单，是时直接设置为已支付
	    	if(Constant.Dict.DICT_BOOLEAN_YES.equals(emsOrder.getType()))
	    	{
	    		emsOrder.setStatus(Constant.Order.EMS_ORDER_STATUS_SUCCESS);
	    	}
	    	// 其他设置为待支付
	    	else
	    	{
	    		emsOrder.setStatus(Constant.Order.EMS_ORDER_STATUS_TOPAY);
	    	}
		}
		// 生成订单
		emsOrderService.save(emsOrder);
		
		model.addAttribute("orderNo", emsOrder.getOrderNo());
		
		// 所选课程插入商品明细表
		EmsCartHis emsCartHis = new EmsCartHis();
		emsCartHis.setOrder(emsOrder);
		emsCartHis.setCreateBy(emsOrder.getCreateBy());
		this.emsCartHisService.copyCart(emsCartHis);
		
		//删除购物车中所选课程
		EmsCart emsCart = new EmsCart();
		emsCart.setCreateBy(emsOrder.getCreateBy());
		this.emsCartService.deleteByCreate(emsCart);
		
		// 更新每件商品应付金额到商品明细表
		if(null != cartListHisBean && null != cartListHisBean.getCartHisList() && cartListHisBean.getCartHisList().size() > 0)
		{
			List<EmsCartHis> cartHisList = cartListHisBean.getCartHisList();
			/*int row = */emsCartHisService.batchUpdateCartHis(cartHisList);
			/*System.out.println(row);*/
		}
		
		addMessage(redirectAttributes, "保存订单成功,报名成功。订单号：" + emsOrder.getOrderNo()); 
		return "redirect:"+Global.getAdminPath()+"/ems/emsOrder/?repage";
	}
	
	@RequiresPermissions("ems:emsOrder:edit")
	@RequestMapping(value = "delete")
	public String delete(EmsOrder emsOrder, RedirectAttributes redirectAttributes) {
		emsOrderService.delete(emsOrder);
		addMessage(redirectAttributes, "删除订单成功");
		return "redirect:"+Global.getAdminPath()+"/ems/emsOrder/?repage";
	}
	
	@RequiresPermissions("ems:emsOrder:cashier")
	@RequestMapping(value = {"cashierTotalMoney"})
	public String cashierTotalMoney(HttpServletRequest request, HttpServletResponse response, Model model) {
		List<Map<String,String>> totalMoneyList = emsOrderService.cashierTotalMoney(); 
		model.addAttribute("totalMoneyList", totalMoneyList);
		return "modules/ems/statistic/emsCashierTotalMoney";
	}
	@RequiresPermissions("ems:emsOrder:cashier")
	@RequestMapping(value = {"cashierDayMoney"})
	public String cashierDayMoney(String dateStr,HttpServletRequest request, HttpServletResponse response, Model model) {
		
		Date date = new Date();
		if(!StringUtils.isBlank(dateStr))
		{
			try {
				date = DateUtils.parseDate(dateStr, "yyyy-MM-dd");
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		model.addAttribute("date", date);
		Map<String,String> param = new HashMap<String, String>();
		param.put("dateStr", dateStr);
		List<Map<String,String>> totalMoneyList = emsOrderService.cashierDayMoney(param); 
		model.addAttribute("totalMoneyList", totalMoneyList);
		return "modules/ems/statistic/emsCashierDayMoney";
	}

}